package org.onvivals.app.weixin.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.binarywang.wxpay.bean.request.WxPayUnifiedOrderRequest;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.github.binarywang.wxpay.service.WxPayService;
import io.undertow.util.BadRequestException;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.onvivals.common.enums.AppFromEnum;
import org.onvivals.common.enums.BillDetailEnum;
import org.onvivals.common.enums.OrderInfoEnum;
import org.onvivals.common.exception.BusinessException;
import org.onvivals.common.utils.IpUtil;
import org.onvivals.module.ums.entity.UmsUser;
import org.onvivals.module.ums.entity.UmsUserRecharge;
import org.onvivals.module.ums.entity.dto.WechatUserDto;
import org.onvivals.module.ums.service.IUmsUserRechargeService;
import org.onvivals.module.ums.service.IUmsUserService;
import org.onvivals.modules.mp.config.WxPayProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * @ClassName 微信支付WeixinPayService
 **/
@Service
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class WeixinPayService {

	private final IUmsUserService userService;
	private final IUmsUserRechargeService userRechargeService;
	private final WxPayService wxPayService;
	private final WxPayProperties properties;

	/**
	 * 统一支付入口
	 *
	 * @param orderId 单号
	 * @param from    来源
	 * @param attach  备注 普通支付还是充值
	 * @param body    内容
	 * @return Object
	 */
	public Object unifyPay(String orderId, String from, String attach, String body) {
		long uid = 0;
		int payPrice = 0;
		BigDecimal bigDecimal = new BigDecimal(100);
		//普通支付
		if (BillDetailEnum.TYPE_3.getValue().equals(attach)) {
		} else { //充值
			UmsUserRecharge userRecharge = userRechargeService.getOne(Wrappers.<UmsUserRecharge>lambdaQuery()
					.eq(UmsUserRecharge::getOrderId, orderId));
			if (userRecharge == null) {
				throw new BusinessException("充值订单不存在");
			}

			if (userRecharge.getPaid().equals(OrderInfoEnum.PAY_STATUS_1.getValue())) {
				throw new BusinessException("该订单已支付");
			}
			uid = userRecharge.getUid();
			payPrice = bigDecimal.multiply(userRecharge.getPrice()).intValue();
		}
		UmsUser member = userService.getById(uid);
		if (member == null) {
			throw new BusinessException("用户错误");
		}
		WechatUserDto wechatUserDto = member.getWxProfile();
		WxPayUnifiedOrderRequest orderRequest = new WxPayUnifiedOrderRequest();
		orderRequest.setOutTradeNo(orderId);
		orderRequest.setTotalFee(payPrice);
		orderRequest.setSpbillCreateIp(IpUtil.getLocalhostIp());
		orderRequest.setNotifyUrl(this.getApiUrl() + "/wechat/notify");
		orderRequest.setBody(body);
		orderRequest.setAttach(attach);

		if (AppFromEnum.WEIXIN_H5.getValue().equals(from)) {
			orderRequest.setTradeType("MWEB");
		} else if (AppFromEnum.APP.getValue().equals(from)) {
			orderRequest.setTradeType("APP");
		} else if (AppFromEnum.PC.getValue().equals(from)) {
			orderRequest.setTradeType("NATIVE");
			orderRequest.setProductId(UUID.fastUUID().toString());
		} else {
			orderRequest.setTradeType("JSAPI");
			if (AppFromEnum.ROUNTINE.getValue().equals(from)) {
				orderRequest.setOpenid(wechatUserDto.getRoutineOpenid());
			} else {
				orderRequest.setOpenid(wechatUserDto.getOpenid());
			}
		}
		try {
			return wxPayService.createOrder(orderRequest);
		} catch (WxPayException e) {
			log.info("支付错误信息：{}", e.getMessage());
			throw new BusinessException(e.getMessage());
		}
	}

	/**
	 * 返回notify url
	 *
	 * @return url
	 */
	private String getApiUrl() {
		String apiUrl = this.properties.getNotifyUrl();
		if (StrUtil.isBlank(apiUrl)) {
			throw new BusinessException("请配置移动端api地址");
		}
		return apiUrl;
	}
}
